'use strict';

/* Controllers */
// signin controller
app.controller('SigninFormController', ['$scope', '$http', '$localStorage', '$sessionStorage', '$state', function ($scope, $http, $localStorage, $sessionStorage, $state) {
    $scope.user = {};
    $scope.authError = null;
    $scope.login = function () {
        $scope.authError = null;
        // Try to login
        $http({
            url: 'uaa/oauth/token',
            method: 'post',
            data: {username: $scope.user.username, password: $scope.user.password, grant_type: "password"},
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                "Authorization": "Basic d2ViX2FwcDo="
            }, transformRequest: function (obj) {
                var str = [];
                for (var p in obj) {
                    str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
                }
                return str.join('&');
            }
        }).then(function (data) {
            var accessToken = data.data["access_token"];
            if (angular.isDefined(accessToken)) {
                $scope.storeAuthenticationToken(accessToken, false);
            }
            $state.go('app.dashboard');
        }, function (x) {
            $scope.authError = 'Server Error';
        });
    };

    $scope.storeAuthenticationToken = function (jwt, rememberMe) {
        if (rememberMe) {
            $localStorage.authenticationToken = jwt;
        } else {
            $sessionStorage.authenticationToken = jwt;
        }
    }
}]);
